package com.jkl.nettyserver.Netty;

import com.jkl.nettyserver.Tool.Zookeeper.ZookeeperClient;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//channel 代表和客户端进行读写的通道 Initializer 初始化，负责添加别的 handler
@Component
public class NettyServerChannelInitializer extends ChannelInitializer<SocketChannel> {
    //添加具体 handler
    final ZookeeperClient zookeeperClient;
    @Autowired
    public NettyServerChannelInitializer(ZookeeperClient zookeeperClient) {
        this.zookeeperClient = zookeeperClient;
    }

    @Override
    protected void initChannel(SocketChannel channel) {
        // 配置链式解码器
        ChannelPipeline pipeline = channel.pipeline();
        //告诉Netty在读取到字节流（ByteBuf）时，自动尝试将这些字节解码为字符串。StringDecoder通常用于TCP Socket连接，因为它处理的是原始的字节数据，并且您期望这些数据是某种字符编码（如UTF-8）的文本。
        //往pipeline链中添加解码器
//        pipeline.addLast("decoder",new StringDecoder(CharsetUtil.UTF_8));
        //往pipeline链中添加编码器
//        pipeline.addLast("encoder",new StringEncoder(CharsetUtil.UTF_8));

        // 解码成HttpRequest
        pipeline.addLast("http-codec",new HttpServerCodec());
        //用于支持大文件或大数据流的分块写入。当你想通过网络发送一个非常大的数据块（例如，一个大文件）时，你可能不希望一次性将整个数据加载到内存中，因为这可能会导致内存溢出。相反，你可能希望将数据分块，并一次发送一个块。
        pipeline.addLast("http-chunked",new ChunkedWriteHandler());
        // 解码成FullHttpRequest
        pipeline.addLast("aggregator",new HttpObjectAggregator(65536));
        //添加心跳
//        pipeline.addLast("idle-state",new IdleStateHandler(6,0,0, TimeUnit.SECONDS));
//        pipeline.addLast(new HeartBeatHandler());
        // 添加WebSocket解编码
        pipeline.addLast(new WebSocketServerProtocolHandler("/ChatScope",null,true,65536,true,true,10000L));
        //处理或转发信息的处理器
        pipeline.addLast(new WebSocketHandler(zookeeperClient));

//        //Socket 连接心跳检测
//        pipeline.addLast("idleStateHandler", new IdleStateHandler(60, 0, 0));
    }
}
